/**
 * 专题图工具箱事件
 */
class Event {
  constructor(_) {
    this.tool = _;
    this._click = this.click.bind(this);
    this._mousemove = this.mousemove.bind(this);
    this.events = [
      { name: 'click', func: this._click },
      { name: 'mousemove', func: this._mousemove }
    ];
  }

  /**
   * 绑定事件
   */
  addEvents() {
    this.events.forEach((event) => {
      if (this.tool.bindEvents.indexOf(event.name) > -1) {
        this.tool.getMap().on(event.name, event.func);
      }
    });
  }

  /**
   * 移除事件
   */
  removeEvents() {
    this.events.forEach((event) => {
      this.tool.getMap().off(event.name, event.func);
    });
  }

  /**
   * 地图点击事件
   * @param {*} e 事件参数
   * @ignore
   */
  click(e) {
    let bound = this.pointToBoundingBox(e.point, 3);
    let features = this.tool.getMap().queryRenderedFeatures(bound, { layers: this.tool.layerIds });
    this.processCallback(this.tool.events.click, e, features);
  }

  /**
   * 地图鼠标移动事件
   * @param {*} e 事件参数
   * @ignore
   */
  mousemove(e) {
    let bound = this.pointToBoundingBox(e.point, 3);
    let features = this.tool.getMap().queryRenderedFeatures(bound, { layers: this.tool.layerIds });
    if (features.length > 0) {
      this.processCallback(this.tool.events.mouseover, e, features);
    } else if(this.tool.events.mouseout) {
      this.tool.events.mouseout();
    }
  }

  /**
   * 将点模型转换为正方形模型
   * @param {*} point
   * @param {*} buffer
   */
  pointToBoundingBox(point, buffer = 0) {
    return [
      [point.x - buffer, point.y - buffer],
      [point.x + buffer, point.y + buffer]
    ];
  }

  /**
   * 触发事件
   * @param {*} event 事件回调方法
   * @param {*} e 事件参数
   * @param {features} features 图形对象
   * @ignore
   */
  processCallback(event, e, features) {
    if(event) {
      if (features.length > 0) {
      // 点击屏幕坐标
        let point = [e.point.x, e.point.y];
        // 点击地图坐标
        let lngLat = e.lngLat.toArray();
        var _features = features.map((feature) => {
          if (feature.layer.id.indexOf(this.tool.layeridPrefix) > -1) {
            return {
              type: 'Feature',
              layer: feature.layer,
              properties: feature.properties,
              geometry: feature.geometry,
              point,
              lngLat
            };
          }
        });
        event(_features);
      }
    }
  }
}

export default Event;


